package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.constants.JwtClaimsConstant;
import com.huike.constants.MessageConstant;
import com.huike.dto.LoginDto;
import com.huike.dto.PageUserDto;
import com.huike.dto.SysUserDto;
import com.huike.entity.Department;
import com.huike.entity.SysUser;
import com.huike.exception.AccountNotFoundException;
import com.huike.exception.BaseException;
import com.huike.exception.PasswordErrorException;
import com.huike.exception.VerificationCodeErrorException;
import com.huike.mapper.DepartmentMapper;
import com.huike.mapper.SysUserMapper;
import com.huike.properties.JwtProperties;
import com.huike.result.PageResult;
import com.huike.result.Result;
import com.huike.service.UserService;
import com.huike.utils.JwtUtil;
import com.huike.utils.RedisCache;
import com.huike.utils.ValidateCodeUtil;
import com.huike.vo.LoginVo;
import com.huike.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserServiceImp implements UserService {


    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 生成图片验证码
     *
     * @param response
     */
    @Override
    public void getCodeImage(HttpServletResponse response) {
        try {
            int width = 110;
            int height = 40;
            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            String randomText = ValidateCodeUtil.drawRandomText(width, height, verifyImg);
            System.out.println("验证码" + randomText);
            redisCache.saveCache("code", randomText);

            response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别

            OutputStream os = response.getOutputStream(); //获取文件输出流

            ImageIO.write(verifyImg, "png", os);//输出图片流

            os.flush();

            os.close();//关闭流

        } catch (IOException e) {

            System.out.println(e.getMessage());

            e.printStackTrace();

        }
    }

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result<LoginVo> userLogin(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        String code = loginDto.getCode();

        if (code == null) {
            //验证码为空
            throw new VerificationCodeErrorException(MessageConstant.CODE_NULL);
        }

        String codeFromRedis = redisCache.getCache("code");

        if (!code.equals(codeFromRedis)) {
            //验证码错误
            throw new VerificationCodeErrorException(MessageConstant.CODE_ERROR);
        }

        SysUser sysUser = sysUserMapper.selectById(1L);
        System.out.println(sysUser);

        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getUserName, userName);
        SysUser sysUserFromMysql = sysUserMapper.selectOne(lqw);

        if (sysUserFromMysql == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        if (!password.equals(sysUserFromMysql.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, sysUserFromMysql.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),// 签名：huike
                jwtProperties.getUserTtl(), // 过期时间：7200000
                claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setUserId(sysUserFromMysql.getUserId());

        sysUserFromMysql.setLoginDate(LocalDateTime.now());
        sysUserMapper.updateById(sysUserFromMysql);

        return Result.success(loginVo);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult<SysUserVo>> list(PageUserDto dto) {
        //查询校验
        if (dto == null) {
            throw new BaseException("参数错误");
        }
        //参数
        String name = dto.getName();
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        String phone = dto.getPhone();
        Short status = dto.getStatus();
        LocalDateTime createTimeBegin = dto.getCreateTimeBegin();
        LocalDateTime createTimeEnd = dto.getCreateTimeEnd();

        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        //昵称
        if (name != null && !name.equals("")) {
            lqw.like(SysUser::getNickName, name);
        }
        //手机号
        if (phone != null && !phone.equals("")) {
            lqw.eq(SysUser::getPhone, phone);
        }
        //状态
        if (status != null) {
            lqw.eq(SysUser::getStatus, status);
        }
        //时间
        if (createTimeBegin != null && createTimeEnd != null) {
            lqw.between(SysUser::getCreateTime, createTimeBegin, createTimeEnd);
        }

        //是否删除
        lqw.eq(SysUser::getDelFlag, 0);
        //查
        Page<SysUser> sysUserPage = sysUserMapper.selectPage(new Page<SysUser>(page, size), lqw);
        //准备Result

        List<SysUser> sysUsers = sysUserPage.getRecords();
        List<SysUserVo> sysUserVoList = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUser,sysUserVo);
            //查询
            String deptName = departmentMapper.selectById(sysUser.getDeptId()).getDeptName();
            sysUserVo.setDeptName(deptName);
            //添加
            sysUserVoList.add(sysUserVo);
        }
        //封装Vo
        PageResult<SysUserVo> sysUserPageResult = new PageResult<>();
        sysUserPageResult.setRecords(sysUserVoList);
        sysUserPageResult.setTotal(sysUserPage.getTotal());
        return Result.success(sysUserPageResult);
    }


    /**
     * 添加用户
     *
     * @param dto
     * @return
     */
    @Override
    public Result add(SysUserDto dto) {
        if (dto == null) {
            throw new BaseException("参数错误");
        }

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(dto,sysUser);
        //补全属性
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setStatus("1");



        sysUserMapper.insert(sysUser);
        return Result.success();
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        if (id == null) {
            throw new BaseException("参数错误");
        }

        //查
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser==null) {
            throw new BaseException("未知错误");
        }

        sysUser.setDelFlag("2");

        //改
        sysUserMapper.updateById(sysUser);

        return Result.success();
    }

    /**
     * 根据id查询回显
     * @param id
     * @return
     */
    @Override
    public Result<SysUser> findById(Integer id) {
        if (id == null) {
            throw new BaseException("参数错误");
        }

        SysUser sysUser = sysUserMapper.selectById(id);

        return Result.success(sysUser);
    }

    /**
     * 修改用户
     * @param dto
     * @return
     */
    @Override
    public Result update(SysUserDto dto) {
        if (dto==null) {
            throw new BaseException("参数错误");
        }

        //查
        SysUser sysUser = sysUserMapper.selectById(dto.getUserId());
        if (sysUser==null) {
            throw new BaseException("未知错误");
        }
        BeanUtils.copyProperties(dto,sysUser);
        sysUser.setUpdateTime(LocalDateTime.now());
        //改
        sysUserMapper.updateById(sysUser);

        return Result.success();
    }
}
